//
//  DetailsOfArticleViewController.m
//  SaltLightDemo
//
//  Created by lzy on 2018/5/8.
//  Copyright © 2018年 lzy. All rights reserved.
//

#import "DetailsOfArticleViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "TestJSObject.h"
#import "MGTabBarController.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "AppDelegate.h"
#import "MGRequestService+My.h"
#import "SLInformationViewController.h"
#import "ProductDetailsViewController.h"
#import "DetailsOfArticleViewController.h"
@interface DetailsOfArticleViewController ()<UIWebViewDelegate,UIScrollViewDelegate>
{
    NSString * string;
    NSString * urls;
    int i;
}
@property (nonatomic , strong) UIWebView *web;
@property (nonatomic , strong) UIButton *backBtn;
@end

@implementation DetailsOfArticleViewController

-(void)setUrl:(NSString *)url
{
    _url = url;
    NSURL * u = [NSURL URLWithString:[NSString stringWithFormat:@"%@",url]];
    NSURLRequest * a = [NSURLRequest requestWithURL:u];
    [self.web loadRequest:a];
    
}

-(UIWebView *)web
{
    if (!_web) {
        
        _web = [[UIWebView alloc]init];
        _web.delegate = self;
        [self.view addSubview:_web];
        [_web mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
        [(UIScrollView *)[[_web subviews] objectAtIndex:0] setBounces:NO];
        for (UIView *_aView in [_web subviews])
        {
            if ([_aView isKindOfClass:[UIScrollView class]])
            {
                [(UIScrollView *)_aView setDelegate:self];
                [(UIScrollView *)_aView setShowsVerticalScrollIndicator:NO];
                //右侧的滚动条
                
                [(UIScrollView *)_aView setShowsHorizontalScrollIndicator:NO];
                //下侧的滚动条
                
            }
        }
    }
    return _web;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"详情";
//    self.fd_prefersNavigationBarHidden = YES;
//    self.url = @"https://www.baidu.com";
    
    // Do any additional setup after loading the view from its nib.
}
/**
 *  截取URL中的参数
 *
 *  @return NSMutableDictionary parameters
 */
- (NSMutableDictionary *)getURLParameters:(NSString *)urlStr {
    
    // 查找参数
    NSRange range = [urlStr rangeOfString:@"?"];
    if (range.location == NSNotFound) {
        return nil;
    }
    
    // 以字典形式将参数返回
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    // 截取参数
    NSString *parametersString = [urlStr substringFromIndex:range.location + 1];
    
    // 判断参数是单个参数还是多个参数
    if ([parametersString containsString:@"&"]) {
        
        // 多个参数，分割参数
        NSArray *urlComponents = [parametersString componentsSeparatedByString:@"&"];
        
        for (NSString *keyValuePair in urlComponents) {
            // 生成Key/Value
            NSArray *pairComponents = [keyValuePair componentsSeparatedByString:@"="];
            NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
            NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
            
            // Key不能为nil
            if (key == nil || value == nil) {
                continue;
            }
            
            id existValue = [params valueForKey:key];
            
            if (existValue != nil) {
                
                // 已存在的值，生成数组
                if ([existValue isKindOfClass:[NSArray class]]) {
                    // 已存在的值生成数组
                    NSMutableArray *items = [NSMutableArray arrayWithArray:existValue];
                    [items addObject:value];
                    
                    [params setValue:items forKey:key];
                } else {
                    
                    // 非数组
                    [params setValue:@[existValue, value] forKey:key];
                }
                
            } else {
                
                // 设置值
                [params setValue:value forKey:key];
            }
        }
    } else {
        // 单个参数
        
        // 生成Key/Value
        NSArray *pairComponents = [parametersString componentsSeparatedByString:@"="];
        
        // 只有一个参数，没有值
        if (pairComponents.count == 1) {
            return nil;
        }
        
        // 分隔值
        NSString *key = [pairComponents.firstObject stringByRemovingPercentEncoding];
        NSString *value = [pairComponents.lastObject stringByRemovingPercentEncoding];
        
        // Key不能为nil
        if (key == nil || value == nil) {
            return nil;
        }
        
        // 设置值
        [params setValue:value forKey:key];
    }
    
    return params;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != alertView.cancelButtonIndex) {
        [Util callAtOnce:alertView.title];
    }
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //    [self.web stringByEvaluatingJavaScriptFromString:@"hidePop()"];
    //同样我们也用刚才的方式模拟一下js调用方法
    
    theBool = true;
    
        NSString * str = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
        self.title = [str length]>0?str:@"详情";
    
    //首先创建JSContext 对象（此处通过当前webView的键获取到jscontext）
    JSContext *context=[self.web valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    //第二种情况，js是通过对象调用的，我们假设js里面有一个对象 testobject 在调用方法
    //首先创建我们新建类的对象，将他赋值给js的对象
    [context setExceptionHandler:^(JSContext *ctx, JSValue *js) {
        NSLog(@"error %@",js);
    }];
    TestJSObject *testJO = [[TestJSObject alloc]init];
    [testJO setGoBackBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:NO];
        });
    }];
    [testJO setJumpAppBlock:^(NSString * str) {
        NSLog(@"fffff %@",str);
        NSDictionary * dic = [self dictionaryWithJsonString:str];
        if([dic[@"jumpType"] isEqualToString:@"app"]){
            if([dic[@"address"] isEqualToString:@"productInfo"]){
                //贷款详情
                int type = [dic[@"type"] intValue];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    ProductDetailsViewController * ctr = [[ProductDetailsViewController alloc]init];
                    ctr.type = type;
                    [self.navigationController pushViewController:ctr animated:YES];
                });
            }else if([dic[@"address"] isEqualToString:@"productList"]){
                //产品列表
                int type = [dic[@"type"] intValue];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    SLInformationViewController * ctr = [[SLInformationViewController alloc]init];
                    ctr.type = type;
                    [self.navigationController pushViewController:ctr animated:YES];
                });
            }
        }else if([dic[@"jumpType"] isEqualToString:@"h5"]){
            if ([dic[@"type"] isEqualToString:@"1"]) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    DetailsOfArticleViewController * ctr = [[DetailsOfArticleViewController alloc]init];
                    ctr.url = dic[@"address"];
                    [self.navigationController pushViewController:ctr animated:YES];
                });
            }
        }
        
    }];
    context[@"util"]=testJO;
}
//json格式字符串转字典：

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        
        return nil;
        
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                         
                                                        options:NSJSONReadingMutableContainers
                         
                                                          error:&err];
    
    if(err) {
        
        NSLog(@"json解析失败：%@",err);
        
        return nil;
        
    }
    
    return dic;
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"request.URL %@  %@",request.URL.absoluteString,[webView stringByEvaluatingJavaScriptFromString:@"document.title"]);
    //    if ([request.URL.absoluteString rangeOfString:@"tel:"].location != NSNotFound) {
    //        NSArray * arr =[request.URL.absoluteString componentsSeparatedByString:@"l:"];
    //        UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:arr[1] message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"呼叫", nil];
    //        [alertView show];
    //        return NO;
    //    }
    urls = request.URL.absoluteString;
    
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    myProgressView.progress = 0;
    theBool = false;
    //0.01667 is roughly 1/60, so it will update at 60 FPS
    myTimer = [NSTimer scheduledTimerWithTimeInterval:0.01667 target:self selector:@selector(timerCallback) userInfo:nil repeats:YES];
    
}
-(void)timerCallback {
    if (theBool) {
        if (myProgressView.progress >= 1) {
            myProgressView.hidden = true;
            [myTimer invalidate];
        }
        else {
            myProgressView.progress += 0.1;
        }
    }
    else {
        myProgressView.progress += 0.05;
        if (myProgressView.progress >= 0.95) {
            myProgressView.progress = 0.95;
        }
    }
}
-(void)goBack
{
    
    if (self.web.canGoBack) {
        [self.web goBack];
    }else
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    self.backBtn.hidden = YES;
}
-(void)dealloc
{
    self.backBtn.hidden = YES;
    [myProgressView removeFromSuperview];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    i++;
    if (i == 1) {
        self.hideDefaultBackButton = YES;
        UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
        self.backBtn = button1;
        [button1 setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
        button1.frame = CGRectMake(17, 0, 50, 44);
        [button1 addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
        button1.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [button1 setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        button1.titleLabel.font = [UIFont systemFontOfSize:16];
        [button1 setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        [button1 setTitle:@"" forState:UIControlStateNormal];
        [self.navigationController.navigationBar addSubview:button1];
        
        NSLog(@"nav  %@",self.navigationController.navigationBar);
        CGFloat progressBarHeight = 1.f;
        CGRect barFrame = CGRectMake(0,0, SCREEN_WIDTH, progressBarHeight);
        myProgressView = [[UIProgressView alloc] initWithFrame:barFrame];
        myProgressView.progressTintColor = [UIColor add_colorWithRGBHexString:@"ffd765"];
        [self.view addSubview:myProgressView];
        
        
        
    }
    self.backBtn.hidden = NO;
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:YES];
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
